package cn.wolfcode.service.impl;

import cn.wolfcode.dao.OrderDao;
import cn.wolfcode.domain.Order;
import cn.wolfcode.domain.Product;
import cn.wolfcode.feign.ProductFeignApi;
import cn.wolfcode.service.OrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
//    @Autowired
//    private RestTemplate restTemplate;
//    //主要操作nacos注册中心的
//    @Autowired
//    private DiscoveryClient discoveryClient;
    @Autowired
    private ProductFeignApi productFeignApi;

    int i=0;
    @Override
    public Order createOrder(Long productId, Long userId) {
        log.info("接收到{}号商品的下单请求,接下来调用商品微服务查询此商品信息", productId);
        //远程调用商品微服务,查询商品信息
        Product product = null;
        //短信验证用到过,,,后端调用后端方法
        //product=restTemplate.getForObject("http://localhost:8081/product/"+productId,
                //Product.class);

        //List<ServiceInstance> instances = discoveryClient.getInstances("product-service");

        //1.负载均衡--随机数
        int index=0;
        //index=new Random().nextInt((instances.size()));
        //ServiceInstance serviceInstance = instances.get(index);

        //2.负载均衡--轮询
        //index=i++%instances.size();
        //ServiceInstance serviceInstance=instances.get(index);

        //3.负载均衡--权重 8081 2  8082 1
//        int[] idx={0,0,1};
//        index=idx[i++%instances.size()];
//        ServiceInstance serviceInstance=instances.get(index);
//
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();

        product=productFeignApi.findByPid(productId);
//        product=restTemplate.getForObject("http://product-service/product/"+productId,Product.class);

        log.info("查询到{}号商品的信息,内容是:{}", productId, JSON.toJSONString(product));
        //创建订单并保存
        Order order = new Order();
        order.setUid(userId);
        order.setUsername("叩丁狼教育");
        order.setPid(productId);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        orderDao.save(order);
        log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));
        return order;
    }
}